//
//  YiFileListView.swift
//  yiplayer
//
//  Created by wkun on 2024/6/17.
//

import Foundation
import SMBClient

class YiFileListView: YiListView {
    
    var filedir: SMBFile?
    var serverModel: YiServerListCellModel?
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        self.navView.rightBtn.isHidden = true
        self.registerCell()
    }
    
    override func registerCell() {
        self.tableView.register(YiFileListViewCell.self, forCellReuseIdentifier: self.reuseid)
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    public func loadDatas(datas: [SMBFile]?, filedir: SMBFile?)  {
        self.datas = datas
        self.filedir = filedir
        self.navView.titleL.text = filedir?.name
        self.tableView.reloadData()
    }
    
    override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        
        if let m = self.model(datas, indexPath) as? SMBFile {
            //不展示隐藏文件
            if m.name.hasPrefix(".") {
                return 0
            }
        }
        
        return super.tableView(tableView, heightForRowAt: indexPath)
    }
    
    override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        super.tableView(tableView, didSelectRowAt: indexPath)
        
        if let m = self.model(datas, indexPath) as? SMBFile {
            if m.isDirectory {
                self.listFiles(file: m)
            }else{
                self.currCtrl()?.showSuccess(m.name)
                
                if let ext = m.path.pathExt() {
                    if ext.isVideo() {
                        //播放之前需要先打开文件
                        m.open(.read) { err in
                            if let error = err {
                                print("Unable to open the file: %@", error);
                            } else {
                                print("File opened: %@", m.name);
                                
                                
                                if let furl = self.fullUrl(file: m) {
                                    self.currCtrl()?.playVideo(url: furl)
                                }
                            }
                        }
                    }else if ext.isAudio() {
                        
                    }else if ext.isPhoto() {
                        
                    }
                }
            }
        }
    }
    
    func listFiles(file:SMBFile?) {
        file?.listFiles({ files, error in
            if let error = error {
                print("Unable to list files: %@", error);
            } else if let files = files{
                print("Found %d files", files.count);
                
                let v = YiFileListView()
                v.serverModel = self.serverModel
                v.loadDatas(datas: files, filedir: file)
                self.currCtrl()?.addListView(v)
            }
        })
    }
}

class YiFileListViewCell: YiListViewCell {
    override var model: Any?{
        didSet{
            super.model = model
            
            if let m = model as? SMBFile {
                
                //home_jpg home_audio home_video home_blank
                var img = "home_doc"
                if m.isDirectory == false {
                    img = "home_blank"
                    if let ext = m.path.pathExt() {
                        if ext.isVideo() {
                            img = "home_video"
                        }else if ext.isAudio() {
                            img = "home_audio"
                        }else if ext.isPhoto() {
                            img = "home_jpg"
                        }
                    }
                }
                
                self.imgView.setImg(img)
                self.textL.text = m.name
            }
        }
    }
}


extension YiFileListView{
    
    //smb://xiaoming:123456@192.168.1.100/cgw/Desktop/1.mp4
    func fullUrl(file: SMBFile?) -> URL? {
        if let file = file {
            let path = file.path
            let user = serverModel?.username ?? ""//"cgw"
            let pwd = serverModel?.pwd ?? ""//"htc"
            var ul = "smb://"
            if user.count > 0 && pwd.count > 0 {
                ul = ul + user + ":" + pwd + "@"
            }else if user.count > 0 && pwd.count == 0 {
                ul = ul + user + "@"
            }
            
            let shareName = file.share.name
            if let host = file.share.server.host {
                ul = ul + host + "/" + shareName
                ul = ul + path
                
//                ul = "smb://" + host + "/" + shareName + path
                
                if let encodedUrlString = ul.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed) {
                    if let url = URL(string: encodedUrlString) {
                        return url
                    }
                }
            }
        }
        return nil
    }
}
